package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.LoginUserDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.DeviceDataGraphVo;
import com.zzyl.nursing.vo.LoginUserVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 老人家属Service业务层处理
 *
 * @author mr.wu
 * @date 2025-05-23
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    /**
     * 用户昵称名前缀集合
     */
    private static List<String> NICK_NAME_PREFIX_LIST = Arrays.asList("钱途无量",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    @Autowired
    private TokenService tokenService;

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public LoginUserVo login(LoginUserDto dto) {
        //1. 调用微信小程序登录接口获取openId
        String openId = wechatService.getOpenId(dto.getCode());
        if (StringUtils.isBlank(openId)) {
            throw new BaseException("获取openId失败");
        }

        //2. 根据openId查询用户数据
        FamilyMember member = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();

        //3. 如果用户不存在，则新增用户（自动注册）
        if (member == null) {
            Collections.shuffle(NICK_NAME_PREFIX_LIST);

            //随机生成昵称
            String nickName = NICK_NAME_PREFIX_LIST.get(0) + RandomStringUtils.randomNumeric(4);

            member = FamilyMember.builder().name(nickName).openId(openId).build();
            boolean result = this.save(member);
            if (!result) {
                throw new BaseException("新增用户失败");
            }
        }

        //4. 判断用户手机号如果不存在，则调用微信获取手机号接口得到手机号
        if (StringUtils.isBlank(member.getPhone())) {
            String phone = wechatService.getPhone(dto.getPhoneCode());
            if (StringUtils.isBlank(phone)) {
                throw new BaseException("获取手机号失败");
            }

            //5. 得到手机号后则完成用户表的更新
            boolean result = this.lambdaUpdate().eq(FamilyMember::getId, member.getId())
                    .set(FamilyMember::getPhone, phone).update();
            if (!result) {
                throw new BaseException("更新手机号失败");
            }
        }

        //6. 生成登录成功用户的令牌（Token）
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("userId", member.getId());//设置用户
        userMap.put("name", member.getName());//用户昵称
        String token = tokenService.createToken(userMap);//生成令牌

        //7. 构建响应数据
        return LoginUserVo.builder().nickName(member.getName()).token(token).build();
    }


    /**
     * 新增或更新老人家属
     *
     * @param familyMember 老人家属对象
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember) {
        // 判断id是否为空
        if (ObjectUtils.isEmpty(familyMember.getId())) {
            // 新增
            // 生成一个随机的用户名，规则是：一个随机的好听的名字+手机号后4位
            Collections.shuffle(NICK_NAME_PREFIX_LIST);
            //随机生成昵称
            String prefix = NICK_NAME_PREFIX_LIST.get(0);
            String nickName = prefix + familyMember.getPhone().substring(7);
            familyMember.setName(nickName);
            familyMemberMapper.insert(familyMember);
        } else {
            // 更新
            familyMemberMapper.updateById(familyMember);
        }
    }

    @Autowired
    private IDeviceDataService deviceDataService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询健康数据
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(DeviceDto dto) {
        Device device = deviceService.lambdaQuery().eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getDeviceName, dto.getDeviceName())
                .one();
        if(device==null) {
            throw new BaseException("设备不存在");
        }

        String deviceDataJsonList = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId());
        if(StringUtils.isBlank(deviceDataJsonList)){
            throw new BaseException("设备数据不存在");
        }

        List<DeviceData> deviceDataList = JSONUtil.toList(deviceDataJsonList, DeviceData.class);
        List<Map<String, Object>> propertyStatusInfo = deviceDataList.stream().map(x -> {
            Map<String, Object> map = new HashMap<>();
            map.put("identifier", x.getFunctionId());
            map.put("value", x.getDataValue());
            map.put("time", x.getAlarmTime().atZone(ZoneId.of("Asia/Shanghai")).toInstant().toEpochMilli());
            return map;
        }).collect(Collectors.toList());

        //将第三位元素心跳与第四位交换，心跳当做第四位元素，这样小程序端显示的就是心跳的值
        Collections.swap(propertyStatusInfo,2,3);

        Map<String,Object> list = new HashMap<>();
        list.put("propertyStatusInfo", propertyStatusInfo);

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("list", list);

        return resultMap;
    }

    /**
     * 按天查询指标数据
     *
     * @param iotId      设备id
     * @param functionId 物模型id
     * @param startTime  查询开始时间
     * @param endTime    查询结束时间
     * @return 每小时数据
     */
    @Override
    public List<DeviceDataGraphVo> queryDeviceDataListByDay(String iotId, String functionId, Long startTime, Long endTime) {
        // 获取一天内每个小时数据的临时结果
        List<DeviceDataGraphVo> dayInstances = DeviceDataGraphVo.getDayInstances(LocalDateTimeUtil.of(startTime));

        // 从数据库中查询一天内每个小时实际数据结果
        List<DeviceDataGraphVo> result = familyMemberMapper.queryDeviceDataListByDay(iotId, functionId, LocalDateTimeUtil.of(startTime), LocalDateTimeUtil.of(endTime));

        // 遍历临时结果，将数据库中查询到的结果拼接进去
        for (DeviceDataGraphVo dayInstance : dayInstances) {
            result.forEach(data -> {
                if (dayInstance.getDateTime().equals(data.getDateTime())) {
                    dayInstance.setDataValue(data.getDataValue());
                }
            });
        }

        return dayInstances;
    }


    /**
     * 按周查询指标数据
     *
     * @param iotId      设备id
     * @param functionId 物模型id
     * @param startTime  查询开始时间
     * @param endTime    查询结束时间
     * @return 每小时数据
     */
    @Override
    public List<DeviceDataGraphVo> queryDeviceDataListByWeek(String iotId, String functionId, Long startTime, Long endTime) {
        // 获取一天内每个小时数据的临时结果
        List<DeviceDataGraphVo> weekInstances = DeviceDataGraphVo.getWeekInstances(LocalDateTimeUtil.of(startTime));

        // 从数据库中查询一天内每个小时实际数据结果
        List<DeviceDataGraphVo> result = familyMemberMapper.queryDeviceDataListByWeek(iotId, functionId, LocalDateTimeUtil.of(startTime), LocalDateTimeUtil.of(endTime));

        // 遍历临时结果，将数据库中查询到的结果拼接进去
        for (DeviceDataGraphVo dayInstance : weekInstances) {
            result.forEach(data -> {
                if (dayInstance.getDateTime().equals(data.getDateTime())) {
                    dayInstance.setDataValue(data.getDataValue());
                }
            });
        }
        return result;
    }
}
